const express=require('express');
const userService=require('../service/userService');
const cookieParser=require('cookie-parser');
const cookieSession=require('cookie-session');


var router=express.Router();

//body-parser(get获取路由,传送数据)
//箭头函数--》匿名函数（有箭头就不用写function）
//注册
router.post('/register',async (req,res,next)=>{
    var user=req.body;
    if(user==undefined||user=={}||user==[]){
        res.send({success:false,msg:'用户名与密码不能为空'})
    }else{
        //await--->同步
         var data=await userService.addUser(user);
        if(data.success){
            //路由发送数据给服务器用send,而不是return
            res.send({success:true,user:data.user}) ;
        }else{
            res.send (data);
        }
    }
});

//登录
//query  默认get方法获取
router.post('/login',async (req,res,next)=>{
    var user=req.body;
    //var cookies=req.cookies;
    if(user==undefined||user=={}||user==[]){
        res.send({success:false,msg:'用户名与密码不能为空'})
    }else {
        var data=await userService.login(user);
        console.log('service:'+data.user.user);
        if(data.success){
            //登录成功对cookie进行操作，同时对session进行操作
        if(user.remember=='true'){
            //res.cookie({name:data.user.name,password:data.user.passeord})
            res.cookie("user",data.user,{maxAge:7*24*60*1000});
        }
            req.session.user =data.user;
        }
        res.send(data);
    }
})

router.use('/logout',(req,res)=>{
    console.log('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa');
    var user=req.session['user'];
    var userCookie=req.cookies['user'];
    if(user==null||user=={}||user==undefined){
        res.send('Havn\'t login in!');
    }else{
        req.session['user']={};
       res.clearCookie('user');
        //res.cookie('user',userCookie,{maxAge:1})
        res.redirect('/index.html');
    }
})
exports.router=router;